package com.atguigu.datastream.test.day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * ClassName: Flink03_Stream_WordCount_unBounded
 * Package: com.atguigu.test
 * Description:
 *
 * @Author ChenJun
 * @Create 2023/4/6 22:23
 * @Version 1.0
 */
public class Flink03_Stream_WordCount_unBounded {
    public static void main(String[] args) throws Exception {

        //1. 创建 flink 的流运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //2. 色湖之并行度
        env.setParallelism(1);

        //3. 通过 段口获取数据  无解数据
        DataStreamSource<String> streamSource = env.socketTextStream("hadoop102", 9999);

        //4. 将一行数据按照空格切分为一个一个的单词, 输出二元组
        SingleOutputStreamOperator<Tuple2<String, Long>> wordStream = streamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Long>> collector) throws Exception {
                String[] words = s.split(" ");
                for (String word : words) {
                    collector.collect(Tuple2.of(word, 1L));
                }

            }
        });

        //5. 通过keyBy对单词进行合并
        KeyedStream<Tuple2<String, Long>, Tuple> keyedStream = wordStream.keyBy(0);

        //6.进行sum计算
        SingleOutputStreamOperator<Tuple2<String, Long>> sum = keyedStream.sum(1);

        //7。打印输出
        sum.print();

        //8.执行
        env.execute();
    }
}
